<template>
  <div class="content">
    <StudentMenu />
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <el-card shadow="never" style="margin-bottom: 10px">
        <header class="flex justify-between items-center mb-6">
          <div>
            <h1 class="text-3xl font-bold text-gray-800">调查问卷列表</h1>
          </div>
          <div class="flex items-center space-x-4">
            <!--            <el-button icon="el-icon-plus" type="text" @click="addGw">审核通过</el-button>-->
            <!--            <el-button icon="el-icon-plus" type="text" @click="addGw">发布新岗位</el-button>
                        <el-button icon="el-icon-edit" type="text" @click="eiditGw">编辑岗位</el-button>-->
          </div>
        </header>
      </el-card>
      <!--      {
      "id": 1,
      "title": "测试标题",
      "description": "测试测试",
      "questions": "[{\"title\":\"你是男的女的？\",\"type\":\"single\",\"options\":[{\"content\":\"男\"},{\"content\":\"女\"}]}]",
      "cjsj": "2025-05-26T16:29:23.143+00:00",
      "fbz": "lls",
      "fbzsfdm": 2
      }-->
      <el-tabs v-model="activeName" >
        <el-tab-pane label="问卷列表" name="first">
          <el-table
              :data="surveyList"
              style="width: 100%"
              highlight-current-row
              @row-dblclick="handleRowDblClick"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="cjsj" label="创建时间" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="问卷详情" name="second">
          <div v-if="selectedSurvey">
            <h3 class="text-lg font-semibold mb-2">{{ selectedSurvey.title }}</h3>
            <p class="mb-4">{{ selectedSurvey.description }}</p>

            <div
                v-for="(q, index) in questionList"
                :key="index"
                class="mb-4"
            >
              <p class="font-semibold">{{ index + 1 }}. {{ q.title }}</p>
              <div v-if="q.type === 'single'">
                <el-radio-group v-model="answers[index]">
                  <el-radio
                      v-for="(opt, i) in q.options"
                      :label="opt.content"
                      :key="i"
                  >{{ opt.content }}</el-radio
                  >
                </el-radio-group>
              </div>
              <div v-else-if="q.type === 'multiple'">
                <el-checkbox-group v-model="answers[index]">
                  <el-checkbox
                      v-for="(opt, i) in q.options"
                      :label="opt.content"
                      :key="i"
                  >{{ opt.content }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
              <div v-else>
                <el-input
                    type="textarea"
                    v-model="answers[index]"
                    placeholder="请输入回答"
                />
              </div>
            </div>
          </div>

            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAnswers">提交</el-button>

        </el-tab-pane>
      </el-tabs>


    </main>
  </div>
</template>

<script>
import StudentMenu from "@/components/student/Student_menu.vue";
import axios from "axios";
import {EventBus} from "@/event-bus";

export default {
  name: "StudentInfo",
  components: { StudentMenu },
  data() {
    return {
      activeName: "first",
      surveyList: [],
      selectedSurvey: null,
      questionList: [],
      answers: [],
      UserInfo:{},
      dialogVisible: false,
    };
  },
  created() {
    this.getLoginUserInfo();
    this.loadSurveys();
  },
  methods: {
    getLoginUserInfo() {
      axios.get('/user/checkSession').then(response => {
        if (!response.data.result) {
          EventBus.$emit('show-auth-popup');
          setTimeout(() => {
            this.$router.push({name: 'StudentLoginView'});
          }, 1000);
        } else {
          this.UserInfo.id = response.data.YHID;
          this.UserInfo.name = response.data.name;
          this.UserInfo.role = response.data.role;
          this.UserInfo.username = response.data.username;
        }
      }).catch(error => {
        EventBus.$emit('show-auth-popup');
        console.error('获取用户信息失败,网络错误！', error.message);
        setTimeout(() => {
          this.$router.push({name: 'StudentLoginView'});
        }, 1000);
      });
    },
    async loadSurveys() {
      try {
        const res = await axios.get("/dcwjk/getDcwjkList?fbzsfdm=2&yhm=lls");
        this.surveyList = res.data.data;
      } catch (err) {
        this.$message.error("加载问卷失败");
      }
    },
    handleRowDblClick(row) {
      this.selectedSurvey = row;
      try {
        this.questionList = JSON.parse(row.questions || "[]");
        this.answers = this.questionList.map((q) =>
            q.type === "multiple" ? [] : ""
        );
        this.activeName = "second";
        this.dialogVisible = true;
      } catch (e) {
        this.$message.error("问卷解析失败");
      }
    },
    async submitAnswers() {
      try {
        await this.$confirm("确定提交问卷吗？");

        let  payload=new FormData();
        payload.append('examid', this.selectedSurvey.id);
        payload.append('yhsfdm', 4);
        payload.append('yhm', this.UserInfo?.username || "anonymous");
        payload.append('answers', JSON.stringify(this.answers));

        await axios.post("/dcwjk/addDcwjkAnswer", payload);

        this.$message.success("问卷提交成功！");
        this.dialogVisible = false;
      } catch (err) {
        if (err !== 'cancel') {
          this.$message.error("提交失败");
          console.error(err);
        }
      }
    }
  },
};
</script>
